package com.bwie.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.fegin.AuthFeginService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserRequest;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthFeginService authFeginService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result sendCode(String phone) {
        User byPhone = authFeginService.findByPhone(phone);
        if(byPhone==null){
            return Result.error("手机号不存在");
        }

        String code = RandomUtil.randomNumbers(4);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return Result.success(code);


    }

    @Override
    public Result Login(UserRequest userRequest) {
        if(StringUtils.isAnyBlank(userRequest.getCode(),userRequest.getPhone())){
            return Result.error("手机号或验证码不能为空");
        }

        User byPhone = authFeginService.findByPhone(userRequest.getPhone());
        if(byPhone==null){
            return Result.error("手机号不存在");
        }
        String code = redisTemplate.opsForValue().get(userRequest.getPhone());
        if(StringUtils.isEmpty(code)){
            return Result.error("验证码无效");
        }

        String userKey = UUID.randomUUID().toString().replaceAll("-", "");
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey, JSONObject.toJSONString(byPhone));

        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setExpireTime("30MIN");
        jwtResponse.setToken(token);
        return Result.success(jwtResponse);

    }

    @Override
    public User userInfo() {
        String token = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(token);
        String user = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSON.parseObject(user,User.class);
    }
}
